package com.qsw.qswcommonlib.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * 图片工具
 */
public abstract class CommonBitmapUtil {
    /**
     * 图片按比例压缩，压缩比例为2的倍数，压缩后的尺寸小于等于指定最大尺寸。会压缩文件大小
     *
     * @param srcBitmap 源Bitmap
     * @return 压缩后的Bitmap
     */
    public static Bitmap compressScale(Bitmap srcBitmap, int maxWidth, int maxHeight) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设为true
        newOpts.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(bis, null, newOpts);
        newOpts.inJustDecodeBounds = false;

        newOpts.inSampleSize = calcuteInSampleSize(newOpts.outWidth, newOpts.outHeight, maxWidth, maxHeight);

        bis = new ByteArrayInputStream(baos.toByteArray());
        return BitmapFactory.decodeStream(bis, null, newOpts);
    }

    /**
     * 计算缩放系数
     *
     * @param srcW 原图的宽
     * @param srcH 原图的高
     * @param maxW 缩放后的最大宽
     * @param maxH 缩放后的最大高
     * @return 缩放系数
     */
    private static int calcuteInSampleSize(int srcW, int srcH, int maxW, int maxH) {
        int inSampleSize = 1;
        if (srcW > maxW || srcH > maxH) {
            inSampleSize = 2;
            while ((srcW / inSampleSize > maxW) || (srcH / inSampleSize > maxH)) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    /**
     * Bitmap质量压缩
     *
     * @param bitmap    源Bitmap
     * @param maxLength 要压缩到的最大大小，单位byte
     * @return 压缩后的Bitmap
     */
    public static Bitmap compressBitmap(Bitmap bitmap, int maxLength) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 质量压缩
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 90;
        while (baos.toByteArray().length > maxLength) {
            // 清空baos
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
            options -= 10;// 每次都减少10
        }
        // 把压缩后的数据baos存放到ByteArrayInputStream中
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        // 根据ByteArrayInputStream数据生成图片
        return BitmapFactory.decodeStream(bais, null, null);
    }
}
